package exam.test11.q3;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.List;

public class Application {

    public RBTree<Integer, Person> createTree() {
        // ########## YOUR CODE STARTS HERE ##########
        RBTree<Integer, Person> rbTree = new RBTree<>();
        for (int i = 0; i < 10; i++) {
            int id = i + 1;
            String name = "Person_" + (char)('A' + i);
            Person person = new Person(id, name, 20 + i % 4, "Student");
            rbTree.insert(i, person);
        }

        return rbTree;
        // ########## YOUR CODE ENDS HERE ##########
    }

    public void saveXML(RBTree<Integer, Person> tree) {
        List<Node> nodeList = tree.preorder();
        // ########## YOUR CODE STARTS HERE ##########
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.newDocument();
            Element rootElement = document.createElement("people");
            document.appendChild(rootElement); //append the root to the document

            //把root加入d这个文件里
            for (Node node : nodeList) {
                Person person = (Person) node.data;
                Element personElement = document.createElement("person");//<Person>..
                personElement.setAttribute("age", Integer.toString(person.getAge()));//<Person id="1">..
                personElement.setAttribute("id", Integer.toString(person.getId()));//<Person id="1">..
                personElement.setAttribute("name", person.getName());//<Person id="1">..
                personElement.setAttribute("occupation",person.getOccupation());//<Person id="1">..

                rootElement.appendChild(personElement);
            }
            Transformer transformer = TransformerFactory.newInstance().newTransformer();

            //set encoding
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            //indent the output document
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            //create document
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new File("people.xml"));
            transformer.transform(source, result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // ########## YOUR CODE ENDS HERE ##########
    }

    public static void main(String[] args) {
        Application application = new Application();
        RBTree<Integer, Person> tree = application.createTree();
        application.saveXML(tree);
    }
}
